<template>
  <div class="user-management">
    <h2 class="title1" style="margin-bottom: 20px;">
      <el-icon :size="25">
        <User />
      </el-icon> 用户管理
    </h2>
    <!-- 查询区域 -->
    <el-card class="box-card query-card" shadow="never" style="margin-bottom: 20px">
      <template #header>
        <div class="card-header">
          <span>查询项</span>
        </div>
      </template>
      <div class="filter-section">
        <div class="filter-item">
          <span>用户名：</span>
          <el-input v-model="filters.username" placeholder="请输入用户名" style="width: 200px" />
        </div>

        <div class="filter-item">
          <span>注册日期：</span>
          <el-date-picker v-model="filters.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 300px; margin-left: 5px" />
        </div>

        <div class="filter-item">
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="success" plain @click="reset">重置</el-button>
        </div>
        <div class="action-button">
          <el-button type="warning" plain @click="handleAddUser">新增用户</el-button>
        </div>

      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="table-header">
          <span style="font-weight: bold;">数据列表</span>
          <div class="action-button">
            <el-button type="success" @click="triggerImport">导入</el-button>
            <el-dialog v-model="importDialogVisible" title="导入用户" width="40%" :close-on-click-modal="false" center>
              <div style="margin-bottom: 35px;">是否需要下载一个用户导入样例表格？</div>
              <div style="display: flex; justify-content: center; gap: 18px;">
                <el-button type="primary" @click="downloadSampleExcel">下载样例表格</el-button>
                <el-button type="success" @click="chooseImportFile">选择文件导入</el-button>
                <input ref="importInputRef" type="file" accept=".xlsx, .xls, csv" @change="handleImportFile"
                  style="display: none;" />
              </div>
            </el-dialog>
            <el-button type="primary" @click="exportToExcel">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 新增：加一个带滚动条的容器 -->
      <div class="table-scroll-wrapper">
        <el-table :data="displayedUsers" border style="width: 100%; margin-top: 10px">
          <el-table-column label="序号" align="center" width="100">
            <template #default="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>

          <!-- 用户名 -->
          <el-table-column prop="name" label="用户名" align="center" min-width="120">
          </el-table-column>

          <!-- 用户邮箱 -->
          <el-table-column prop="email" label="用户邮箱" align="center" min-width="160">
          </el-table-column>

          <!-- 创建事件 -->
          <el-table-column prop="createTime" label="注册时间" align="center" min-width="160">
          </el-table-column>
          <!-- 账号状态 -->
          <el-table-column label="账号状态" align="center" min-width="120">
            <template #default="{ row }">
              <el-tag :type="statusTagType(row.status)" size="small">{{ row.status }}</el-tag>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column label="操作" align="center" min-width="120">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="showEditDialog(row)">
                修改
              </el-button>
              <el-button type="danger" size="small" @click="deleteUser(row)">
                删除
              </el-button>

            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination background layout="prev, pager, next, sizes, total" :total="totalUsers"
          :page-sizes="[2, 5, 10, 20]" :page-size="pageSize" :current-page="currentPage" :pager-count="5"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 用户信息弹窗 -->
    <el-dialog v-model="dialogVisible" title="用户信息" width="580px" :close-on-click-modal="false" center>
      <div class="user-detail-card">
        <!-- 原有关键信息区块 -->
        <div class="info-block">
          <div class="detail-item">
            <span class="detail-label">用户邮箱：</span>
            <div class="detail-content">{{ selectedUser.email }}</div>
          </div>
          <div class="detail-item">
            <span class="detail-label">用户名：</span>
            <div class="detail-content">{{ selectedUser.name }}</div>
          </div>
          <div class="detail-item">
            <span class="detail-label">手机号：</span>
            <div class="detail-content">{{ selectedUser.phone || '-' }}</div>
          </div>
        </div>

        <div class="info-block" style="margin-top: 16px">
          <div class="detail-item">
            <span class="detail-label">所在地：</span>
            <div class="detail-content">{{ selectedUser.location || '未填写' }}</div>
          </div>
          <div class="detail-item">
            <span class="detail-label">生日：</span>
            <div class="detail-content">{{ selectedUser.birthday || '未设置' }}</div>
          </div>
        </div>

        <!-- 头像与简介区块 -->
        <div class="info-block" style="margin: 16px 0">
          <div class="detail-item">
            <span class="detail-label">头像：</span>
            <div class="avatar-placeholder"></div>
          </div>
          <div class="detail-item">
            <span class="detail-label">简介：</span>
            <div class="bio-content">{{ selectedUser.bio || '暂无个人介绍' }}</div>
          </div>
        </div>

        <!-- 原状态操作区块 -->
        <div class="info-block">
          <div class="detail-item">
            <span class="detail-label">账号状态：</span>
            <el-radio-group v-model="selectedUser.status">
              <el-radio label="正常" />
              <el-radio label="封禁" />
            </el-radio-group>
          </div>
        </div>

        <!-- 操作按钮保持原有位置 -->
        <div class="action-buttons">
          <el-button type="primary" class="confirm-btn" @click="confirmStatusChange">
            确认修改
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 新增用户弹窗 -->
    <el-dialog v-model="addUserDialogVisible" title="新增用户" width="400px" :close-on-click-modal="false" center>
      <div class="add-user-form">
        <div class="form-row">
          <span class="form-label">用户邮箱：</span>
          <el-input v-model="addUserForm.email" placeholder="请输入用户邮箱" />
        </div>
        <div class="form-row">
          <span class="form-label">用户名：</span>
          <el-input v-model="addUserForm.name" placeholder="请输入用户名" />
        </div>
        <div class="form-row">
          <span class="form-label">密码：</span>
          <el-input v-model="addUserForm.password" placeholder="请输入用户密码" type="password" show-password />
        </div>
        <div class="form-actions">
          <el-button @click="addUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddUserConfirm">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessageBox, ElMessage, ElNotification } from 'element-plus'
import md5 from 'js-md5'
import { useRouter } from 'vue-router'
import * as XLSX from 'xlsx'
// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(0)
// 筛选条件
const filters = ref({
  username: '',
  dateRange: []
})
// 文件输入
const importDialogVisible = ref(false)
const importInputRef = ref(null)
// 弹窗相关状态
const dialogVisible = ref(false)
const addUserDialogVisible = ref(false)
const selectedUser = ref({
  email: '',
  name: '',
  status: '正常'
})
const addUserForm = ref({
  email: '',
  name: '',
  password: ''
})
const statusOptions = ['正常', '封禁']

// 用户数据
const users = ref([])

// 获取用户数据
const fetchUsers = async () => {
  try {
    const response = await axios.get('http://localhost:8181/user/list', {
      params: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        userName: filters.value.username
      },
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue'),
      }
    })
    if (response.data.code === 200) {
      const { records, total } = response.data.data
      users.value = records.map(user => ({
        id: user.userId,
        email: user.email,
        name: user.name || '未填写',
        phone: user.phoneNum || '未填写',
        location: user.location || '未填写',
        birthday: user.birthday || '未设置',
        bio: user.bio || '暂无个人介绍',
        createTime: user.createTime || '未知',
        subscriptionStatus: user.subscriptionEnum === '普通' ? '未订阅' : '已订阅',
        status: user.bannedStatus || '正常'
      }))
      totalUsers.value = total
      ElMessage.success('获取用户数据成功')
    } else {
      ElMessage.error('获取用户数据失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
  }
}

// 过滤后的用户列表（直接使用后端返回的数据，无需额外过滤）
const filteredUsers = computed(() => users.value)

// 分页显示数据
const displayedUsers = computed(() => filteredUsers.value)

// 分页处理
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchUsers()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchUsers()
}

// 查询操作
const search = () => {
  currentPage.value = 1
  fetchUsers()
}

const reset = () => {
  filters.value.username = ''
  filters.value.dateRange = []
  currentPage.value = 1
  fetchUsers()
}

// 导出用户数据
const exportToExcel = async () => {
  try {
    // 获取所有用户数据
    const response = await axios.get('http://localhost:8181/user/getUserAll', {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code === 200) {
      const users = response.data.data || []
      // 构造表头和数据
      const data = [
        ['序号', '用户ID', '用户名', '电话', '邮箱', '介绍', '注册时间', '生日', '账号状态'],
        ...users.map((user, idx) => [
          idx + 1,
          user.userId || '',
          user.name || '',
          user.phoneNum || '',
          user.email || '',
          user.bio || '',
          user.createTime || '',
          user.birthday || '',
          user.bannedStatus || ''
        ])
      ]
      // 创建工作表和工作簿
      const worksheet = XLSX.utils.aoa_to_sheet(data)
      const workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workbook, worksheet, '用户数据')
      // 导出
      XLSX.writeFile(workbook, '用户数据.xlsx')
      ElMessage.success('导出成功')
    } else {
      ElMessage.error(response.data.message || '导出失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
  }
}

// 导入用户
const triggerImport = () => {
  importDialogVisible.value = true
}
const downloadSampleExcel = () => {
  // 构造样例数据
  const data = [
    ['邮箱', '用户名', '手机号', '介绍', '生日'],
    ['test1@example.com', '张三', '13800000000', '示例用户', '2000-01-01'],
    ['test2@example.com', '李四', '13900000000', '示例用户2', '2001-02-02']
  ]
  const worksheet = XLSX.utils.aoa_to_sheet(data)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '用户导入样例')
  XLSX.writeFile(workbook, '用户导入样例.xlsx')
}
const chooseImportFile = () => {
  importInputRef.value && importInputRef.value.click()
}
// 文件处理
const handleImportFile = async (e) => {
  const file = e.target.files[0]
  if (!file) return;
  const ext = file.name.split('.').pop().toLowerCase()
  if (!['xlsx', 'xls', 'csv'].includes(ext)) {
    ElMessage.error('仅支持Excel或csv文件')
    e.target.value = ''
    return;
  }

  const reader = new FileReader()
  reader.onload = async (evt) => {
    const arrayBuffer = evt.target.result
    const workbook = XLSX.read(new Uint8Array(arrayBuffer), { type: 'array' })
    const sheetName = workbook.SheetNames[0]
    const sheet = workbook.Sheets[sheetName]
    const json = XLSX.utils.sheet_to_json(sheet, { header: 1 })
    if (json.length === 0) {
      ElMessage.error('导入文件为空')
      e.target.value = ''
      return
    }
    // 检测是否包含email
    const header = json[0].map(h => (h || '').toString().trim().toLowerCase())
    let emailIdx = header.indexOf('邮箱')
    if (emailIdx === -1) emailIdx = header.indexOf('email')
    if (emailIdx === -1) {
      ElMessage.error('文件必须包含“邮箱”或“email”列')
      e.target.value = ''
      return
    }
    // 其他字段索引
    const nameIdx = header.indexOf('姓名') !== -1 ? header.indexOf('姓名') : header.indexOf('用户名') !== -1 ? header.indexOf('用户名') : header.indexOf('name')
    const phoneIdx = header.indexOf('手机号') !== -1 ? header.indexOf('手机号') : header.indexOf('phone')
    const bioIdx = header.indexOf('介绍') !== -1 ? header.indexOf('介绍') : header.indexOf('bio')
    const birthdayIdx = header.indexOf('生日') !== -1 ? header.indexOf('生日') : header.indexOf('birthday')

    // 检查邮箱为空但有其他数据的行
    const rows = json.slice(1)
    let hasInvalid = false
    const userList = []
    rows.forEach((row) => {
      const email = row[emailIdx]
      const hasOtherData = row.some((cell, i) => i !== emailIdx && cell && cell.toString().trim() !== '')
      if ((!email || email.toString().trim() === '') && hasOtherData) {
        hasInvalid = true
      }
      if (email && email.toString().trim() !== '') {
        const emailStr = email.toString().trim()
        const password = md5(emailStr.split('@')[0] || 'emotionMaster')
        userList.push({
          email: emailStr,
          password: password,
          name: nameIdx !== -1 && row[nameIdx] ? row[nameIdx].toString().trim() : '',
          phoneNum: phoneIdx !== -1 && row[phoneIdx] ? row[phoneIdx].toString().trim() : '',
          bio: bioIdx !== -1 && row[bioIdx] ? row[bioIdx].toString().trim() : '',
          birthday: birthdayIdx !== -1 && row[birthdayIdx] ? excelDateToString(row[birthdayIdx]) : ''
        })
      }
    })
    if (hasInvalid) {
      ElMessage.error('文件中存在无法导入的用户（邮箱为空但有其他数据）')
      e.target.value = ''
      return
    }
    if (userList.length === 0) {
      ElMessage.error('未检测到任何邮箱数据')
      e.target.value = ''
      return
    }
    // 调用邮箱检测接口
    try {
      const emails = userList.map(user => user.email)
      const response = await axios.put(
        `http://localhost:8181/user/emailCheck/${emails.join(',')}`,
        {},
        {
          headers: {
            [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
          }
        }
      )
      if (response.data.code === 200) {
        ElMessage.success(response.data.message || '邮箱检测成功')
      } else {
        ElMessage.error(response.data.message || '邮箱检测失败')
        e.target.value = ''
        return
      }
      // 逐个注册
      const now = new Date()
      const yyyy = now.getFullYear()
      const mm = String(now.getMonth() + 1).padStart(2, '0')
      const dd = String(now.getDate()).padStart(2, '0')
      const createTime = `${yyyy}-${mm}-${dd}`
      let successCount = 0
      let failCount = 0
      for (const user of userList) {
        try {
          const res = await axios.post(
            'http://localhost:8181/user/register',
            {
              email: user.email,
              name: user.name,
              password: user.password,
              phoneNum: user.phoneNum,
              bio: user.bio,
              birthday: user.birthday,
              createTime: createTime
            },
            {
              headers: {
                [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
              }
            }
          )
          if (res.data.code === 200) {
            successCount++
          } else {
            failCount++
          }
        } catch (err) {
          failCount++
        }
        await new Promise(resolve => setTimeout(resolve, 500))
      }
      ElNotification({
        title: '导入结果',
        message: `成功导入 ${successCount} 个用户，失败 ${failCount} 个用户`,
        type: 'success'
      })
    } catch (err) {
      console.error(err)
      e.target.value = ''
      return
    }
  }
  e.target.value = ''
  reader.readAsArrayBuffer(file)
}
const excelDateToString = (serial) => {
  if (typeof serial !== 'number') return serial
  const utc_days = Math.floor(serial - 25569)
  const utc_value = utc_days * 86400
  const date_info = new Date(utc_value * 1000)
  const yyyy = date_info.getFullYear()
  const mm = String(date_info.getMonth() + 1).padStart(2, '0')
  const dd = String(date_info.getDate()).padStart(2, '0')
  return `${yyyy}-${mm}-${dd}`
}
// 弹窗操作
const originalStatus = ref('')
const showEditDialog = (user) => {
  selectedUser.value = { ...user }
  originalStatus.value = user.status // 保存原始状态
  dialogVisible.value = true
}

const confirmStatusChange = async () => {
  try {
    console.log(selectedUser.value)
    if (selectedUser.value.status === '封禁' && originalStatus.value !== '封禁') {
      await ElMessageBox.confirm(
        '确定要将用户状态修改为封禁吗？该操作将限制用户登录！',
        '危险操作确认',
        {
          confirmButtonText: '确认封禁',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }
      )
    }
    console.log(selectedUser.value.id);
    // 调用后端接口更新用户状态
    const response = await axios.post(
      'http://localhost:8181/user/ban',
      {
        userId: selectedUser.value.id,
        bannedStatus: selectedUser.value.status
      },
      {
        headers: {
          [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
        }
      }
    )

    if (response.data.code === 200) {
      ElMessage.success('状态更新成功')
      dialogVisible.value = false

      // 调用 fetchUsers 更新本地用户数据
      await fetchUsers()
    } else {
      ElMessage.error(response.data.message || '状态更新失败')
      selectedUser.value.status = originalStatus.value
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
    selectedUser.value.status = originalStatus.value
  }
}

const deleteUser = async (user) => {
  try {
    // 弹出确认框
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.name}" 吗？此操作不可撤销！`,
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
    )

    // 调用后端接口删除用户
    const response = await axios.delete(
      `http://localhost:8181/user/deleteUser/${user.id}`, // 将 id 作为路径参数
      {
        headers: {
          [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
        }
      }
    )

    if (response.data.code === 200) {
      ElMessage.success('用户删除成功')

      // 调用 fetchUsers 更新本地用户数据
      await fetchUsers()
    } else {
      ElMessage.error(response.data.message || '用户删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('请求失败，请检查后端服务')
    }
  }
}



// 新增用户操作
const handleAddUser = () => {
  addUserForm.value = {
    email: '',
    name: '',
    password: ''
  }
  addUserDialogVisible.value = true
}

const handleAddUserConfirm = async () => {
  try {
    // 简单表单验证
    if (!addUserForm.value.email || !addUserForm.value.name || !addUserForm.value.password) {
      return ElMessage.warning('请填写所有字段')
    }
    const encryptedPassword = md5(addUserForm.value.password)
    const now = new Date()
    const yyyy = now.getFullYear()
    const mm = String(now.getMonth() + 1).padStart(2, '0')
    const dd = String(now.getDate()).padStart(2, '0')
    const createTime = `${yyyy}-${mm}-${dd}`
    // 调用后端接口新增用户
    const response = await axios.post(
      'http://localhost:8181/user/register',
      {
        email: addUserForm.value.email,
        name: addUserForm.value.name,
        password: encryptedPassword,
        createTime: createTime
      },
      {
        headers: {
          [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
        }
      }
    )

    if (response.data.code === 200) {
      ElMessage.success('用户新增成功')
      addUserDialogVisible.value = false
      // 调用 fetchUsers 更新用户列表
      await fetchUsers()
    } else {
      ElMessage.error(response.data.message || '用户新增失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
  }
}
// 根据状态返回标签类型
const statusTagType = (status) => {
  switch (status) {
    case '正常':
      return 'success'; // 绿色标签
    case '封禁':
      return 'danger'; // 红色标签
    default:
      return 'info'; // 默认蓝色标签
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management {
  min-height: 100vh;
}

.box-card {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.query-card .card-header {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  font-size: 14px;
}

.el-tag {
  padding: 0 12px;
  height: 28px;
  line-height: 26px;
}


/* 用户信息弹窗样式 */
.user-detail-card {
  padding: 0 24px 24px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  min-height: 40px;
}

.detail-label {
  width: 80px;
  color: #606266;
  font-weight: 500;
  flex-shrink: 0;
}

.detail-content {
  color: #303133;
  font-size: 14px;
}

.avatar-placeholder {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #f0f2f5;
}

.status-group {
  display: flex;
  gap: 20px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 40px;
  margin-top: 30px;
}

.action-btn {
  width: 120px;
  height: 36px;
  border-radius: 18px;
}

/* 新增用户弹窗样式 */
.add-user-form {
  padding: 10px 0 0 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 22px;
  width: 100%;
}

.form-label {
  width: 80px;
  color: #333;
  font-weight: 500;
  text-align: right;
  margin-right: 10px;
  flex-shrink: 0;
}

.el-input {
  flex: 1;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-top: 30px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-item {
    width: 100%;
    justify-content: space-between;
  }

  .el-date-picker {
    width: 100% !important;
  }

  .action-buttons {
    gap: 20px;
  }

  .action-btn {
    width: 100px;
  }
}

.title1 {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-button {
  margin-left: auto;
  display: flex;
  gap: 15px;
}

.table-scroll-wrapper {
  max-height: 560px;
  /* 限制表格区域高度 */
  overflow-y: auto;
  /* 超出部分显示滚动条 */
  margin-top: 10px;
}
</style>